﻿using SqlDataAccess;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QuanLyBanHang
{
	public partial class F930_Thong_ke_san_pham_ban_chay : Form
	{
		public F930_Thong_ke_san_pham_ban_chay()
		{
			InitializeComponent();
			set_define_events();
		}

		#region Members
		BKIQuanLyBanHangEntities db = new BKIQuanLyBanHangEntities();
		#endregion

		#region Private Methods
		private void set_define_events()
		{
			this.Load += F930_Thong_ke_san_pham_ban_chay_Load;
			this.m_cmd_xem_bao_cao.Click += m_cmd_xem_bao_cao_Click;
		}

		private void load_data_to_grid()
		{
			var v_lst_chi_tiet_hoa_don_ban = db.GD_CT_HOA_DON_BAN
								.Where(x =>
									(x.GD_HOA_DON_BAN.NGAY_BAN >= m_dtp_tu_ngay.Value
										&& x.GD_HOA_DON_BAN.NGAY_BAN <= m_dtp_den_ngay.Value)
									&& (x.DM_SAN_PHAM.TEN_SAN_PHAM.Contains(m_txt_loc_du_lieu.Text)
										|| x.DM_SAN_PHAM.MA_SAN_PHAM.Contains(m_txt_loc_du_lieu.Text)
										|| m_txt_loc_du_lieu.Text.Equals("")
										))
									.ToList();
			var v_lst_thong_ke = db.DM_SAN_PHAM
				.OrderBy(x => x.MA_SAN_PHAM)
				.ToList()
				.Select(x => new
				{
					SAN_PHAM = x.MA_SAN_PHAM + " - " + x.TEN_SAN_PHAM,
					SO_LUONG = v_lst_chi_tiet_hoa_don_ban.Where(ct => ct.ID_SAN_PHAM == x.ID).Sum(ct => ct.SO_LUONG),
					SO_NGUOI_MUA = v_lst_chi_tiet_hoa_don_ban.Where(ct => ct.ID_SAN_PHAM == x.ID).Select(a=>a.GD_HOA_DON_BAN.ID_KHACH_HANG).Distinct().Count()
				})
				.OrderByDescending(x=>x.SO_LUONG)
				.ToList();
			m_grv.DataSource = v_lst_thong_ke;
			m_grv.Columns[0].HeaderText = "Sản phẩm";
			m_grv.Columns[0].Width = 200;
			m_grv.Columns[1].HeaderText = "Số lượng bán";
			m_grv.Columns[2].HeaderText = "Số người mua";
			m_grv.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
		}

		#endregion

		#region Events
		void m_cmd_xem_bao_cao_Click(object sender, EventArgs e)
		{
			try
			{
				load_data_to_grid();
			}
			catch (Exception v_e)
			{
				MessageBox.Show(v_e.ToString());
			}
		}

		void F930_Thong_ke_san_pham_ban_chay_Load(object sender, EventArgs e)
		{
			try
			{
				load_data_to_grid();

				// Gán giá trị ban đầu cho datetime picker
				DateTime v_dat_dau_nam = new DateTime(DateTime.Now.Year, 1, 1);
				m_dtp_tu_ngay.Value = v_dat_dau_nam;
				m_dtp_den_ngay.Value = DateTime.Now;
			}
			catch (Exception v_e)
			{
				MessageBox.Show(v_e.ToString());
			}
		}

        private void m_cmd_quay_lai_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception v_e)
            {
                MessageBox.Show(v_e.ToString());
            }
        }
		#endregion
	}
}
